"use strict";
const Service = require("egg").Service;
const mongoose = require("mongoose");
class OrderService extends Service {
  // 创建订单（不需要微信支付模拟下单调用）（不需要微信支付模拟下单调用）
  async createOrder(payload) {
    const { ctx, app } = this;
    const db = ctx.model.Order;
    payload.OrderStatus = 0;
    const res = await db.create(payload);
    // 自提生成取餐码
    if (payload.orderType === 0) {
      const lastOrder = await db
        .find({ orderType: 0 }, {}, { sort: "-takeMealCode" })
        .limit(1);
      await db.updateOne(
        { _id: res._id },
        { takeMealCode: lastOrder[0].takeMealCode + 1 }
      );
    }
    // 库存自减，销量自增
    const skuList = ctx.model.Attrdetail;
    const goods = ctx.model.Goods;
    for (const item of payload.goods) {
      if (item.sid?.length) {
        await skuList.updateOne(
          { sid: item.sid },
          { $inc: { stock: -item.quantity } }
        );
      }
      await goods.updateOne(
        { _id: item.goodsId },
        { $inc: { stock: -item.quantity, saleNum: item.quantity } }
      );
    }
    // 推送订单通知
    app.io.emit("orderInform", 0)
    return { msg: "成功" };
  }
  // 获取订单详情
  async getOrderDetail(_id) {
    const { ctx } = this;
    const res = await ctx.model.Order.aggregate([
      { $match: { _id: new mongoose.Types.ObjectId(_id) } },
      {
        $lookup: {
          localField: "addressId",
          foreignField: "_id",
          from: "Useraddress",
          as: "addressInfo",
        },
      },
    ]);
    console.log(res);
    return { msg: "成功", data: res[0] };
  }
  // 微信支付
  async wxPay(params) {
    const { ctx } = this;
    const db = ctx.model.Order;
    params.OrderStatus = 0;
    const { openid, ...payload } = params;
    const orderInfo = await db.create(payload);
    // const orderInfo = await ctx.model.Order.aggregate([{ $match: { _id: new mongoose.Types.ObjectId(_id) } }, { $lookup: { localField: "userId", foreignField: "_id", from: "Userinfo", as: "userInfo" } }, { $unwind: "$userInfo" }]);
    const url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";

    const { appid, mchid } = ctx.app.config.wx;
    const body = {
      appid,
      mchid,
      description: "茶百道小程序下单",
      out_trade_no: ctx.generateOutTradeNo(),
      attach: orderInfo._id,//附带参数：订单id
      notify_url: "http://6bdewn.natappfree.cc/api/wx/notify_url",//暂时使用的本地内网穿透的地址
      amount: {
        total: 100 * orderInfo.payPrice
      },
      payer: {
        openid
      }
    }

    const headers = {
      Authorization: ctx.generateAuthSign(JSON.stringify(body)),
      Accept: "application/json",
      "Content-Type": "application/json"
    }

    const data = await fetch(url, { headers, body: JSON.stringify(body), method: 'POST' })
    const json = await data.json();
    console.log(json);
    if (json.status !== 200) {
      return { code: 401, error: json.message, succss: false }
    }
    const prepay_id = json.data.prepay_id;
    return { msg: "成功", data: ctx.generatePaySign(prepay_id) }
  }
}

module.exports = OrderService;
